package com.fate.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fate.constant.MenuConstant;
import com.fate.domain.SysMenu;
import com.fate.mapper.SysMenuMapper;
import com.fate.service.SysMenuService;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {


    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据用户id查菜单
     * 这里我们需要用到缓存
     * redis的菜单就是单纯的list  树形的菜单结构 在代码转
     * 1.先判断缓存有没有
     * 2.缓存有 直接用
     * 3.缓存没有在查询  放入缓存
     * 4.组装菜单
     *
     * @param sysUserId
     * @return
     */
    @Override
    public List<SysMenu> findUserMenu(Long sysUserId) {
        String menuStr = redisTemplate.opsForValue().get(MenuConstant.MENU_PREFIX + sysUserId);
        List<SysMenu> menus = null;
        if (StringUtils.hasText(menuStr)) {
            // 转一下
            menus = JSON.parseArray(menuStr, SysMenu.class);

        } else {
            // 查询 再进去
            menus = sysMenuMapper.findSysUserMenu(sysUserId);
            if (CollectionUtils.isEmpty(menus)) {

                redisTemplate.opsForValue().set(MenuConstant.MENU_PREFIX + sysUserId, JSON.toJSONString(menus), Duration.ofDays(7));
            }
        }
        // 转换树形菜单
        return translateTree(menus, 0L);
    }

    /**
     * 转换树菜单的
     *
     * @param menus
     * @param pid
     * @return
     */
    private List<SysMenu> translateTree(List<SysMenu> menus, Long pid) {
        // 1.根据菜单深度来选择 组装方式  双重for
        // 2.拿到顶级菜单

        List<SysMenu> root = menus.stream().filter(sysMenu ->
                sysMenu.getParentId().equals(pid)
        ).collect(Collectors.toList());
        // 3.循环顶级菜单 匹配子菜单
        root.forEach(r->{
            List<SysMenu> child = menus.stream().filter(sysMenu -> sysMenu.getParentId().equals(r.getMenuId())).collect(Collectors.toList());
            r.setList(child);
        });

        return root;
    }
}
